<template>
  <div :class="this.customActiveKey === 'tab1' ? 'main' : 'main2'">
    <a-form :form="form" class="user-layout-login" ref="formLogin" id="formLogin" selfUpdate>
      <a-tabs :activeKey="customActiveKey" :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
              @change="handleTabClick">
        <a-tab-pane key="tab1" tab="账号密码登陆">
          <a-form-item>
            <a-input size="large"
                     v-decorator="['username', validatorRules.username, { validator: this.handleUsernameOrEmail }]"
                     type="text" placeholder="请输入帐户名">
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <a-form-item>
            <a-input v-decorator="['password', validatorRules.password]" size="large" type="password"
                     autocomplete="false" placeholder="请输入密码">
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
      <a-form-item v-if="customActiveKey === 'tab1'">
        <a-checkbox-group @change="onChangeRememberMe" v-model="formLogin.rememberMe">
          <a-checkbox value="1">记住密码</a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item style="margin-top: 24px" v-if="customActiveKey === 'tab1'">
        <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="loginBtn"
                  @click.stop.prevent="handleSubmit" :disabled="loginBtn">登录
        </a-button>
      </a-form-item>
      <a-form-item style="margin-top: 24px" v-if="customActiveKey === 'tab2'">
        <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="registerBtn"
                  @click.stop.prevent="register" :disabled="registerBtn">注册
        </a-button>
      </a-form-item>
    </a-form>
    <a-modal title="登录部门选择" :width="450" :visible="departVisible" :closable="false" :maskClosable="false">
      <template slot="footer">
        <a-button type="primary" @click="departOk">确认</a-button>
      </template>

      <a-form>
        <a-form-item :labelCol="{ span: 4 }" :wrapperCol="{ span: 20 }" style="margin-bottom: 10px"
                     :validate-status="validate_status">
          <a-tooltip placement="topLeft">
            <template slot="title">
              <span>您隶属于多部门，请选择登录部门</span>
            </template>
            <a-avatar style="backgroundcolor: #87d068" icon="gold"/>
          </a-tooltip>
          <a-select @change="departChange" :class="{ 'valid-error': validate_status == 'error' }" placeholder="请选择登录部门"
                    style="margin-left: 10px; width: 80%">
            <a-icon slot="suffixIcon" type="gold"/>
            <a-select-option v-for="d in departList" :key="d.id" :value="d.orgCode">
              {{ d.departName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <user-password ref="userPassword" @clearInput="clearInput"></user-password>
  </div>
</template>

<script>
//import md5 from "md5"
import api from '@/api'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import {mapActions} from 'vuex'
import {timeFix} from '@/utils/util'
import Vue from 'vue'
import {ACCESS_TOKEN} from '@/store/mutation-types'
import JGraphicCode from '@/components/jeecg/JGraphicCode'
import {putAction, postAction, getAction} from '@/api/manage'
import UserPassword from '@/components/tools/UserPassword'
import CryptoJS from 'crypto-js'

export default {
  components: {
    TwoStepCaptcha,
    JGraphicCode,
    UserPassword,
  },
  data() {
    return {
      customActiveKey: 'tab1',
      // salaryFlags: '',
      loginBtn: false,
      registerBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        smsSendBtn: false,
      },
      model: {},
      formLogin: {
        username: '',
        password: '',
        captcha: '',
        mobile: '',
        rememberMe: ['1'],
      },
      labelCol: {
        xs: {span: 20},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      validatorRules: {
        username: {rules: [{required: true, message: '请输入账户名!', validator: 'click'}]},
        password: {rules: [{required: true, message: '请输入密码!', validator: 'click'}]},
      },
      url: {
        register: '/user/tempUser/add',
        startProcess: '/process/extActProcess/startMutilProcess',
        toPY: '/user/tempUser/convertToPinYin',
        checkName: '/user/tempUser/checkUserName',
      },
      flowCode: 'dev_bms_temp_user', // 审批固定字段
      verifiedCode: '',
      inputCodeContent: '',
      inputCodeNull: true,

      departList: [],
      departVisible: false,
      departSelected: '',
      currentUsername: '',
      validate_status: '',
      currentDepartId: '',  //当前用户登录时的部门id
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = {'X-Access-Token': token}
    sessionStorage.setItem('loginRouter', window.location.href)
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    toPY(val) {
      console.log(val.target.value)
      getAction(this.url.toPY, {realName: val.target.value}).then((res) => {
        console.log(res)
        if (res.success) {
          this.form.setFieldsValue({tempusername: res.result.pinyin})
        }
      })
    },
    handleUsernameOrEmail(rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      if (this.customActiveKey === 'tab1') {
      }
      this.form.resetFields()
    },
    handleSubmit() {
      let that = this
      let loginParams = {}
      if (that.formLogin.rememberMe.toString() === '1') {
        loginParams.remember_me = true
      } else {
        loginParams.remember_me = false
      }
      // 使用账户密码登陆
      that.form.validateFields(['username', 'password', 'inputCode'], {force: true}, (err, values) => {
        if (!err) {
          loginParams.username = values.username
          //loginParams.password = md5(values.password)
          loginParams.password = values.password
          if (that.formLogin.rememberMe.toString() === '1') {
            that.setCookie(loginParams.username, loginParams.password, 7)
          } else {
            //清空Cookie
            that.clearCookie()
          }
          localStorage.setItem('rememberMe', that.formLogin.rememberMe.toString())
          that
            .Login(loginParams)
            .then((res) => {
              this.departConfirm(res)
            })
            .catch((err) => {
              // if (err.message == '密码为初始密码') {
              //   that.$refs.userPassword.show(this.form.getFieldValue('username'))
              // } else {
              that.requestFailed(err)
              // }
            })
        }
      })
    },
    //密码修改成功后，清楚输入框里的内容
    clearInput() {
      this.form.setFieldsValue({username: ''})
      this.form.setFieldsValue({password: ''})
    },
    getCaptcha(e) {
      e.preventDefault()
      let that = this

      this.form.validateFields(['mobile'], {force: true}, (err) => {
        if (!err) {
          this.state.smsSendBtn = true
          let interval = window.setInterval(() => {
            if (that.state.time-- <= 0) {
              that.state.time = 60
              that.state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)
          this.$http
            .post(api.SendSms, {mobile: that.formLogin.mobile})
            .then((res) => {
              setTimeout(hide, 2500)
              this.$notification['success']({
                message: '提示',
                description: '验证码获取成功，您的验证码为：' + res.result.captcha,
                duration: 8,
              })
            })
            .catch((err) => {
              setTimeout(hide, 1)
              clearInterval(interval)
              that.state.time = 60
              that.state.smsSendBtn = false
              this.requestFailed(err)
            })
        }
      })
    },
    loginSuccess() {
      //这里不需要考虑当前部门为空的状态，因为新建用户必须选择一个或者多个部门
      Vue.ls.set('CURRENT_DEPARTID', this.currentDepartId, 7 * 24 * 60 * 60 * 1000)   //把当前用户登录时的部门id存起来  (参数名，参数值，参数有效期)
      this.loginBtn = false
      this.$router.push({name: 'dashboard'})
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`,
      })
    },
    requestFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
        duration: 4,
      })
      this.loginBtn = false
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(/^1\d{10}$/).test(value)) {
        callback()
      } else {
        callback('您的手机号码格式不正确!')
      }
    },
    validateInputCode(rule, value, callback) {
      if (!value || this.verifiedCode == this.inputCodeContent) {
        callback()
      } else {
        callback('您输入的验证码不正确!')
      }
    },
    generateCode(value) {
      this.verifiedCode = value.toLowerCase()
    },
    inputCodeChange(e) {
      this.inputCodeContent = e.target.value
      if (!e.target.value || 0 == e.target.value) {
        this.inputCodeNull = true
      } else {
        this.inputCodeContent = this.inputCodeContent.toLowerCase()
        this.inputCodeNull = false
      }
    },
    departConfirm(res) {
      if (res.success) {
        let multi_depart = res.result.multi_depart
        //0:无部门 1:一个部门 2:多个部门
        if (multi_depart == 0) {
          //无部门，当前部门为空
          this.currentDepartId = ''
          this.loginSuccess()
          this.$notification.warn({
            message: '提示',
            description: `您尚未归属部门,请确认账号信息`,
            duration: 3,
          })
        } else if (multi_depart == 2) {
          this.departVisible = true
          this.currentUsername = this.form.getFieldValue('username')
          this.departList = res.result.departs
        } else {
          //只有一个部门时，当前部门直接存第一条的部门id
          this.currentDepartId = res.result.departs && res.result.departs.length !== 0 ? res.result.departs[0].id : ''
          this.loginSuccess()
        }
      } else {
        this.requestFailed(res)
        this.Logout()
      }
    },
    departOk() {
      if (!this.departSelected) {
        this.validate_status = 'error'
        return false
      }
      let obj = {
        orgCode: this.departSelected,
        username: this.form.getFieldValue('username'),
      }
      putAction('/sys/selectDepart', obj).then((res) => {
        if (res.success) {
          //多个部门时，当前部门存选择的部门id
          this.currentDepartId = this.departList && this.departList !== 0 ? this.departList.filter(item => item.orgCode === this.departSelected)[0].id : ''
          this.departClear()
          this.loginSuccess()
        } else {
          this.requestFailed(res)
          this.Logout().then(() => {
            this.departClear()
          })
        }
      })
    },
    departClear() {
      this.departList = []
      this.departSelected = ''
      this.currentUsername = ''
      this.departVisible = false
      this.validate_status = ''
    },
    departChange(value) {
      console.log(value)
      this.validate_status = 'success'
      this.departSelected = value
    },
    /*记住密码功能*/
    onChangeRememberMe(e) {
      if (e.toString() === '1') {
        this.formLogin.rememberMe = e
      }
    },
    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date() //获取时间
      var pwd = CryptoJS.AES.encrypt(c_pwd, 'secret key 123') //使用CryptoJS方法加密
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays) //保存的天数
      //字符串拼接cookie
      window.document.cookie = 'usernameDT' + '=' + c_name + ';path=/;expires=' + exdate.toGMTString()
      window.document.cookie = 'passwordDT' + '=' + pwd + ';path=/;expires=' + exdate.toGMTString()
    },
    //获取cookie
    getCookie() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split('; ') //这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split('=') //再次切割
          //判断查找相对应的值
          if (arr2[0] == 'usernameDT') {
            this.form.setFieldsValue({username: arr2[1]}) //保存到保存数据的地方
          } else if (arr2[0] == 'passwordDT') {
            //解密
            var bytes = CryptoJS.AES.decrypt(arr2[1].toString(), 'secret key 123')
            var plaintext = bytes.toString(CryptoJS.enc.Utf8) //拿到解密后的密码（登录时输入的密码）
            this.form.setFieldsValue({password: plaintext})
          }
        }
      }
    },
    //清除cookie
    clearCookie() {
      this.setCookie('', '', -1) //修改2值都为空，天数为负1天就好了
    },
  },
  mounted() {
    /*获取cookie*/
    if (localStorage.getItem('rememberMe') !== null || localStorage.getItem('rememberMe') === '1') {
      this.getCookie()
    }
  },
}
</script>
<style lang="scss" scoped>
.main2 {
  min-width: 260px;
  width: 50%;
  margin: 0 auto;
  border: 1px solid #ccc;
  background: #fff;
  border-radius: 2%;
  border-top-left-radius: 15%;
  border-bottom-right-radius: 15%;
  box-shadow: 0 0 10px #fff;
  border: 1px solid #fff;
  padding: 30px;

  input {
    width: 50%;
  }
}
</style>
<style lang="scss" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
<style>
.valid-error .ant-select-selection__placeholder {
  color: #f5222d;
}
</style>